<?php

namespace Home\Controller;

use Home\Model\ClassModel;
use Home\Model\SigninModel;
use Think\Controller;

class TaskController extends BaseController
{
    public function __construct()
    {
        parent::__construct();
        if ($this->user['role'] == 2) {
            $this->error('学生才可以上传作业');
        }
    }


    public function index()
    {
        $choose = M('Task'); // 实例化User对象
        $query = $choose->where('stu_id', $this->user['id']);
        $count = $query->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count, 10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $query->order('create_time')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        foreach ($list as $key => $item) {
            $class = (new ClassModel())->where('id', $item['class_id'])->select()[0];;
            $item['class'] = $class['name'];
            $list[$key] = $item;
        }
        $this->assign('list', $list);// 赋值数据集
        $this->assign('page', $show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    public function create()
    {
        $choose = M('ChooseClass'); // 实例化User对象
        $list = $choose->where('stu_id', $this->user['id'])->select();
        foreach ($list as $key => $item) {
            $class = (new ClassModel())->where('id', $item['class_id'])->select()[0];;
            $item['class'] = $class['name'];
            $list[$key] = $item;
        }
        $this->assign('list', $list);
        $this->display(); // 输出模板
    }


    public function store()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->savePath = '/uploads/'; // 设置附件上传（子）目录
        // 上传文件
        $info = $upload->upload();
        if (!$info) {// 上传错误提示错误信息
            $this->retError($upload->getError());
        }

        $path = '/uploads' . $info['task']['savepath'] . $info['task']['savename'];

        $choose = M('Task'); // 实例化User对象
        $data['stu_id'] = $this->user['id'];
        $data['class_id'] = I('post.class_id');
        $data['task'] = $path;
        $data['create_time'] = time();
        $data['update_time'] = time();
        $choose->create($data);
        $result = $choose->add();
        if (!$result) {
            $this->retError('新增失败');
        } else {
            $this->retSuccess();
        }
    }

}